import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import { AppDispatch } from 'store'

export interface SignState {
  signList: Sign[]
  commonSignList: Sign[]
}

const initialState: SignState = {
  signList: [],
  commonSignList: []
}
export const signSlice = createSlice({
  name: 'sign',
  initialState,
  reducers: {
    // 添加符号
    addSign(state, action: PayloadAction<Sign>) {
      state.signList.push({ ...action.payload, id: Date.now() })
    },
    // 删除符号
    deleteSign(state, action: PayloadAction<number | undefined>) {
      state.signList = state.signList.filter(item => item.id !== action.payload)
      state.commonSignList = state.commonSignList.filter(item => item.id !== action.payload)
    },
    // 修改符号
    editSign(state, action: PayloadAction<Sign>) {
      state.signList.find((item, index, signList) => {
        if (item.id === action.payload.id) {
          signList[index] = action.payload
        }
        return item.id === action.payload.id
      })
    },
    // 添加常用符号
    addCommonSign(state, action: PayloadAction<Sign>) {
      const findSign = state.commonSignList.find(item => item.id === action.payload.id)
      if (findSign) {
        // 计算符号的最新分数
        findSign.score += Date.now()
        // 重新排序
        state.commonSignList = state.commonSignList.sort((a, b) => -(a.score - b.score))
      } else if (state.commonSignList.length === 20) {
        // 常用符号超过极限，则新加入元素顶替最后一个元素位置
        state.commonSignList[state.commonSignList.length - 1] = { ...action.payload, score: Date.now() }
      } else {
        // 新增常用符号
        state.commonSignList.push({ ...action.payload, score: Date.now() })
      }
    },
    // 清空常用符号
    clearCommonSign(state) {
      state.commonSignList = []
    }
  }
})

// 解构出每个 reducer 对应的 action
export const { addSign, deleteSign, editSign, addCommonSign, clearCommonSign } = signSlice.actions

// 异步添加符号
export const addSignAsync = (signItem: Sign) => async (dispatch: AppDispatch) =>
  new Promise((resolve, reject) => {
    setTimeout(async () => {
      await dispatch(addSign(signItem))
      resolve(true)
    }, 1000)
  })

const signReducers = signSlice.reducer
export default signReducers
